package com.atguigu.campusintelligentassistantsystem.controller;

import com.atguigu.campusintelligentassistantsystem.entity.CampusCard;
import com.atguigu.campusintelligentassistantsystem.entity.CampusCardTransaction;
import com.atguigu.campusintelligentassistantsystem.service.CampusCardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

@RestController
@RequestMapping("/api/campus-card")
@CrossOrigin(origins = "*")
public class CampusCardController {

    @Autowired
    private CampusCardService campusCardService;

    /**
     * 根据学生ID获取校园卡信息
     * @param studentId 学生ID
     * @return 校园卡信息
     */
    @GetMapping("/{studentId}")
    public ResponseEntity<CampusCard> getCampusCard(@PathVariable Long studentId) {
        CampusCard card = campusCardService.getCampusCardByStudentId(studentId);
        if (card != null) {
            return ResponseEntity.ok(card);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 创建校园卡
     * @param studentId 学生ID
     * @param initialBalance 初始余额
     * @return 校园卡信息
     */
    @PostMapping
    public ResponseEntity<CampusCard> createCampusCard(@RequestParam Long studentId, 
                                                       @RequestParam BigDecimal initialBalance) {
        CampusCard card = campusCardService.createCampusCard(studentId, initialBalance);
        return ResponseEntity.ok(card);
    }

    /**
     * 校园卡充值
     * @param cardId 校园卡ID
     * @param amount 充值金额
     * @return 更新后的校园卡信息
     */
    @PostMapping("/{cardId}/recharge")
    public ResponseEntity<CampusCard> recharge(@PathVariable Long cardId, @RequestParam BigDecimal amount) {
        CampusCard card = campusCardService.recharge(cardId, amount);
        if (card != null) {
            return ResponseEntity.ok(card);
        } else {
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 校园卡消费
     * @param cardId 校园卡ID
     * @param amount 消费金额
     * @return 更新后的校园卡信息
     */
    @PostMapping("/{cardId}/consume")
    public ResponseEntity<CampusCard> consume(@PathVariable Long cardId, @RequestParam BigDecimal amount) {
        CampusCard card = campusCardService.consume(cardId, amount);
        if (card != null) {
            return ResponseEntity.ok(card);
        } else {
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 获取校园卡交易记录
     * @param cardId 校园卡ID
     * @return 交易记录列表
     */
    @GetMapping("/{cardId}/transactions")
    public ResponseEntity<List<CampusCardTransaction>> getTransactionHistory(@PathVariable Long cardId) {
        List<CampusCardTransaction> transactions = campusCardService.getTransactionHistory(cardId);
        return ResponseEntity.ok(transactions);
    }
}